package com.helloUIBinder.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.helloUIBinder.model.BlogPost;
import com.helloUIBinder.model.BlogPostCodec;
import org.fusesource.restygwt.client.JsonEncoderDecoder;

import java.util.ArrayList;
import java.util.List;

public class ProjectJsonParser {

    public static <T> T parseJsonValue(Class<T> mappingClass, String jsonString) {
        JsonEncoderDecoder<T> codec = null;
        if (mappingClass.equals(BlogPost.class)) {
            codec = GWT.create(BlogPostCodec.class);
        }
        if (codec == null) {
            return null;
        } else {
            T other = codec.decode(JSONParser.parseStrict(jsonString));
            return other;
        }
    }

    public static <T> JSONValue getJsonFromEntity(Class<T> mappingClass, T object) {
        JsonEncoderDecoder<T> codec = null;
        if (mappingClass.equals(BlogPost.class)) {
            codec = GWT.create(BlogPostCodec.class);
        }
        if (codec == null) {
            return null;
        } else {
            JSONValue jsonValue = codec.encode(object);
            return jsonValue;
        }
    }

    public static <T> List<T> parseJsonArray(Class<T> mappingClass, String jsonString) {
        JSONValue jsonValue = JSONParser.parseStrict(jsonString);
        JSONArray jsonArray = jsonValue.isArray();

        JsonEncoderDecoder<T> decoder = null;
        if (mappingClass.equals(BlogPost.class)) {
            decoder = GWT.create(BlogPostCodec.class);
        }

        if (decoder == null) {
            return null;
        } else {
            List<T> resultList = new ArrayList<T>();
            for (int index = 0; index < jsonArray.size(); index++) {
                resultList.add(decoder.decode(jsonArray.get(index)));
            }
            return resultList;
        }
    }

    public static List<String> parseStringArray(String jsonString) {
        JSONValue jsonValue = JSONParser.parseStrict(jsonString);
        JSONArray jsonArray = jsonValue.isArray();

        List<String> result = new ArrayList<String>();

        for (int index = 0; index < jsonArray.size(); index++) {
            result.add(jsonArray.get(index).toString().replaceAll("\"", ""));
        }
        return result;
    }
}
